package net.tooeye.easymes.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import net.tooeye.easymes.common.BaseActivity;
import net.tooeye.easymes.common.NetworkUtil;
import net.tooeye.easyplus.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class SfctaSelectActivity extends BaseActivity {

    private ListView listView;
    private String[] data = {"正在从服务器获取数据....."};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sfcta_select);
        hideActionBar();
        listView = findViewById(R.id.sfctaListView);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.list_item_sfcta,data);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = (String) ((TextView)view.findViewById(R.id.textViewSfcta)).getText();
                Intent intent = new Intent();
                intent.putExtra("sfcta",text);
                setResult(1,intent);
                SfctaSelectActivity.this.finish();
            }
        });
        GetSfctaList();
    }

    private  void GetSfctaList(){
        Map<String,String> params = new HashMap<>();
        params.put("clientId","android");
        String url = "http://" + this.GetHost()+ "/api/cms/mw";
        @SuppressLint("HandlerLeak") Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                JSONArray jsonArray;
                try {
                    jsonArray = new JSONArray((String)msg.obj);
                    int length = jsonArray.length();
                    String[] listData = new String[length];
                    for (int i = 0;i<length;i++){
                        listData[i] = jsonArray.getJSONObject(i).getString("mW002");
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(SfctaSelectActivity.this,
                            R.layout.list_item_sfcta,listData);
                    listView.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        NetworkUtil.getInstance().get(SfctaSelectActivity.this,url,params,handler,1,GetToken());
    }
}
